
/* 
    图表展示控件
*/

import React, {useCallback, useEffect} from 'react';
// 引入ECharts主模块
import * as echarts from "echarts";
import _ from 'lodash'

import './index.css';

// 文章图表实例
let articleChart = null;

// 数据
const optionForArticle = {
    title:{
        text:'文章统计图'
    },
    tooltip:{
        trigger: 'item',
        formatter: "{b} : {c} ({d}%)"
    },
    series: [
        {
            type: 'pie',
            itemStyle:{
                normal:{
                    label:{
                        show: true,
                        formatter: '{b} : {c} ({d}%)'
                    },
                    labelLine :{show:true}
                }
            }

        }
    ]
}


export default function EchartsCard(props) {

    const {data} = props

    const createChartData = useCallback(()=>{
        const chartData = [];
        data.forEach(item=>{
            chartData.push({
                value:item.count,
                name:item.tagName
            })
        })
        return chartData
    },[data])

    const createCharts = useCallback((target,option,resize=true)=>{
        let charts = echarts.init(document.getElementById(target));
        charts.setOption(option);
        if(resize){
            window.onresize = _.debounce(
                ()=>{
                    console.log('resize');
                    charts.resize()
                },500)
        }
        return charts;
    },[])

    useEffect(()=>{
        optionForArticle.series[0].data = createChartData()
        articleChart = createCharts('echarts-article',optionForArticle);
        setTimeout(()=>{
            articleChart.resize()
        })
    },[createChartData, createCharts])

    useEffect(()=>{
        optionForArticle.series[0].data = createChartData()
        articleChart.setOption(optionForArticle)
    },[createChartData])




    return (
        <div className='echarts-wrapper'>
            <div id='echarts-article'/>
        </div>
    )
}
